package com.zzhua.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 关闭csrf
                .authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/r3").hasRole("admin")
                .antMatchers("/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                    // .successForwardUrl("/login-success") // 登录成功之后，转发到此url
                    .successHandler(
                            // 主要是想登录成功之后修改掉浏览器地址栏的url,所以改为重定向而非转发
                            (request, response, authentication) ->
                                    response.sendRedirect("/login-success"))
                    .loginProcessingUrl("/doLogin")
                    .loginPage("/login")
                    .permitAll()
                .and()
                .logout()
                    .logoutUrl("/doLogout")
                    .logoutSuccessUrl("/login")

        ;
    }

 // 配置用户信息

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // 角色和权限的区别就是：角色前面多了个ROLE_
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1","ROLE_admin").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
        // return new CustomizeUserDetailsService();
    }

 // 密码匹配器

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


}
